<?php

namespace addons\helper\controller\wxapp;

use addons\helper\controller\wxapp\Base;
use app\admin\model\Fields;


class ProjectBase extends Base
{
    protected $noNeedLogin = ['test'];
    protected $model = null;
    protected $fiveindustryArr = [];
    protected $streetArr = [];
    protected $industryCategoryArr = [];
    protected $chargedep_data = null;
    protected $pre = '';
    protected $groupIds = [];
    protected $library_id = null;
    protected $action = ACTION_EDIT;
    protected $config = [
        'limit'             => 10,
        // 'tabField'          => '',
        'searchPlaceholder' => '请输入项目名称搜索',
        'multi'             => true,
        'search'            => true,
        'filter'    => true,
        'fieldContent' => [
            'status' => [
                '-1' => '待提交',
                '0' => '已审核',
                '1'=> '待审核'
            ],
            'tagstatus' =>[
                '-1' => 'warning',
                '0' => 'success',
                '1'=> 'danger'
            ]
        ],
        'auth' => [
            'add'  => [
                'name' => '添加',
                'url'  => 'project/signed/add',
            ],
            'edit'  => [
                'name' => '编辑',
                'url'  => 'project/edit',
            ],
            'multi' => [
                'del'  => [
                    'name'        => '删除',
                    'color'       => '#e74c3c',
                    'icon'        => 'fa-trash',
                    'url'         => 'project/multi'
                ]
            ],
            'more' => [
                'del'  => [
                    'name'  => '删除',
                    'color' => '#e74c3c',
                    'url'   => 'project/del'
                ],
            ],
        ],

    ];
    public function _initialize()
    {
        parent::_initialize();
        // $this -> year = $this -> request -> get('year',date('Y'));
        // $this->model = new \app\admin\model\Project([],$this -> year);
        // $this->year = 2020;
        $this->model = new \app\admin\model\Project();

        // $this->config['data']['isSuperAdmin']  = $this->isSuperAdmin();
        // $this->config['data']['pre'] = $this->pre;
        // $this->config['data']['year'] = $this -> year;
        // // var_dump($this->tablename);
        $this->config['fieldContent']['five_industry_id'] = $this->getSelectList('five_industry');
        $this->config['fieldContent']['industry_category_ids'] = $this->getSelectList('industry_category');
        $this->config['fieldContent']['chargedep_ids'] = $this->getSelectList('chargedep');
        $this->config['fieldContent']['carrier_id'] = $this->getSelectList('carrier');
        $this->config['fieldContent']['project_source_ids'] = $this->getSelectList('activity');
        $this->config['fieldContent']['planned_street_ids'] = $this->getSelectList('chargedep',['group_id'=>5]);
        $this->config['fieldContent']['settle_street_ids'] = $this->getSelectList('chargedep',['group_id'=>5]);
        $this->config['fieldContent']['investment_attribute_ids'] = $this->getSelectList('investor_attribute');

        $this->config['fieldContent']['is_access'] = ['是'=>'是','否'=>'否'];
        $this->config['fieldContent']['is_land'] = ['是'=>'是','否'=>'否'];


    }

    public function index()
    {

        $this->config['auth'] =  [
            // 'add'  => [
            //     'name' => '添加',
            //     'url'  => 'project/signed_add',
            // ],
            // 'edit'  => [
            //     'name' => '编辑',
            //     'url'  => 'project/edit',
            // ],
            // 'multi' => [
            //     'del'  => [
            //         'name'        => '删除',
            //         'color'       => '#e74c3c',
            //         'icon'        => 'fa-trash',
            //         'url'         => 'auth.admin/del'
            //     ]
            // ],
            // 'more' => [
            //     'del'  => [
            //         'name'  => '删除',
            //         'color' => '#e74c3c',
            //         'url'   => 'auth.admin/del'
            //     ],
            // ],
        ];

        $groupIds = $this->getGroupIds();

        $showAna = true;
        if(/*in_array(GROUP_DISTRICTUNIT,$groupIds) || */in_array(GROUP_STREET,$groupIds) || in_array(GROUP_SOE,$groupIds))
        {
            $chargedep_data = $this->auth->getChargedep();
            if($chargedep_data){
                $chargedep_id = $chargedep_data->chargedep_id;
                $this->whereExtend[] = ['exp',Db::raw("FIND_IN_SET($chargedep_id,chargedep_ids)")];
                $this->assignconfig('chargedep_id',$chargedep_id);
            }
            $showAna = false;
        }

        return self::__baselist();
    }


    public function test() {
        $fields =  $this->formatField();
        pr($fields);
    }

     public function __baselist()
    {
        //设置过滤方法
        // $this->whereExtend['p.is_delete'] = 0;
        $where_delete = 'p.is_delete=0';
        $groupIds = $this->getGroupIds();
        $showAna = true;
        if(in_array(GROUP_STREET,$groupIds) || in_array(GROUP_SOE,$groupIds))
        {
            $chargedep_data = $this->getChargedep();
            if($chargedep_data){
                $chargedep_id = $chargedep_data->chargedep_id;
                $where_delete .= " and p.chargedep_ids IN (".$chargedep_id.")";
                // $this->whereExtend[] = ['exp',Db::raw("FIND_IN_SET($chargedep_id,chargedep_ids)")];
                $this->assignconfig('chargedep_id',$chargedep_id);
            }
            $showAna = false;
        }
        $this->request->filter(['strip_tags']);
        if ($this->request->isPost()) {
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $exp = new \think\db\Expression('field(status,1,0,-1)');
            $this->config['field'] = $this->formatField()['field'];
            $this->config['rules'] = $this->formatField()['rules'];
            $this->config['rulesMessage'] = $this->formatField()['rulesMessage'];
            $where_search = 'p.progress_status_id<9 ';
            $exp = new \think\db\Expression('field(p.status,0,-1,1,2,3)');
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $total = $this->model->alias('p')
                ->join('project_stage s','p.id=s.project_id','left')
                ->join('project_centralcontact c','p.id=c.project_id','left')
                ->where($where)
                ->where($where_search)
                ->where($where_delete)
                ->where($this->whereExtend)
                ->order($exp)
                // ->order($sort, $order)
                ->group('p.name')
                ->count();
            $list = $this->model->alias('p')
                ->join('project_stage s','p.id=s.project_id','left')
                ->join('project_centralcontact c','p.id=c.project_id','left')
                ->field('p.*,s.project_id,s.project_stage_time,c.leader_ids,c.leader_names,c.receive_time,c.receive_time_desc,c.contact_typeid')
                ->where($where)
                ->where($where_search)
                ->where($where_delete)
                ->order($exp)
                ->where($this->whereExtend)
                ->order($this->sortExtend)
                // ->order($sort, $order)
                ->limit($offset, $limit)
                ->group('p.name')
                ->select();

            // if(isset($list))
            // {
            //     foreach($list as $key => $value)
            //     {
            //         $plan_time = $this->plan->where(['project_id'=>$value['id'],'is_standard'=>0])->min('plan_time');
            //         $list[$key]['plan_time'] = $plan_time ? $plan_time : "" ;
            //         $list[$key]['local_time'] = time();
            //     }
            // }
            // $update_total = $this->model->alias('p')
            //     ->join('project_stage s','p.id=s.project_id','left')
            //     ->join('project_centralcontact c','p.id=c.project_id','left')
            //     ->where($where)
            //     ->where($where_search)
            //     ->where($where_delete)
            //     ->where('p.status=1')
            //     ->where($this->whereExtend)
            //     ->order($sort, $order)
            //     ->group('p.name')
            //     ->count();
            // if($update_total>0)
            //     $percent = number_format($update_total/$total*100)."%";
            // else
            //     $percent = 0;

            // $sum = array('update_total'=>$update_total,'total'=>$total,'percent'=>$percent);

            $list = collection($list)->toArray();
            $result = array("total" => $total, "rows" => $list);


            $data = [
                'tabList'  => $this->tabList,
                'dataList' => $result,
                'config'   => $this->config
            ];
            $this->success('ok', $data);
        }
        return $this->view->fetch();
    }


    public function edit() {
        $ids = $this->request->get('ids');
        $row = $this->model->get($ids);

        if (!$row) {
            $this->error(__('No Results were found'));
        }

        if ($this->request->isPost()) {
            $data = [];
            $params = $this->request->post("row/a");
            if ($params) {
                if(isset($params['memo']) && $params['memo'])
                    $data['memo'] = $params['memo'];

                $field = $this->request->post("item_id");
                $field_row = Fields::where(['table_name'=>$this->tablename, 'item_id'=>$field])->find();
                if(!$field_row)
                    $this->error('未找到此项');

                if($params['value'] == PENDING_TEXT)
                    $params['value'] = PENDING;

                $field_name = str_replace('id','name', $field);

                $params_field = 'tmp_'.$field;
                $params_field_name = str_replace('id','name', $params_field);
                $log_data_all = [];
                $log_data = [];
                $log_data['field'] = $field;
                $log_data['label'] = $field_row['item_label'];
                $log_data['info'] = $params['desc_value'];  //
                $log_data['status'] = STATUS_SUBMIT;

                $data[$params_field.'_status'] =  STATUS_SUBMIT;
                $data[$params_field.'_submit_desc'] = $params['desc_value'];
                $data[$params_field] = $params['value'];

                $log_data['original_value'] = $row[$field] == PENDING ? PENDING_TEXT : $row[$field];
                $log_data['value'] = $params['value'] == PENDING ? PENDING_TEXT : $params['value'];



                if($field_row['item_type'] == "select" || $field_row['item_type'] == "selects")
                {
                    $data[$params_field] = is_array($params['value'])?implode(",",$params['value']):$params['value'];
                    $rule = json_decode($field_row['item_rule'], true);
                    if(is_string($rule['datasource'])){
                        $tb_name = $rule['datasource'];
                        $data[$params_field_name] =  $this->getSelectText($tb_name,$params['value']);
                    }else
                        $data[$params_field_name] = $rule['datasource'][$params['value']];

                    $log_data['original_value'] = $row[$field_name];
                    $log_data['value'] = $data[$params_field_name];
                }

                if($field_row['item_type'] == "datetime" || $field_row['item_type'] == "date")
                {
                    $log_data['original_value'] = $row[$field.'_desc'];
                    $log_data['value'] = $params['value'] == PENDING ? PENDING_TEXT : $params['value'];
                    if($params['value'] == PENDING)
                    {
                        $data[$params_field.'_desc'] = PENDING_TEXT;
                    }
                    else
                    {
                        $data[$params_field.'_desc'] = $params['value'];
                    }
                }
                if($this->isSuperAdmin())
                {
                    $data[$field] = $data[$params_field];
                    $data[$params_field] = null;
                    $data[$params_field.'_submit_desc'] = null;
                    $data[$params_field.'_status'] = STATUS_PASS;
                    if($field_row['item_type'] == 'select' || $field_row['item_type'] == 'selects')
                    {
                        $data[$field_name] = $data[$params_field_name];
                        $data[$params_field_name] = null;

                    }
                    if($field_row['item_type'] == "datetime" ||$field_row['item_type'] == "date")
                    {
                        $data[$field.'_desc'] = $data[$params_field.'_desc'];
                        $data[$params_field.'_desc'] = null;
                    }
                }
                $log_data_all[] = $log_data;
                //  echo "<pre>";
                // print_r($data);
                // print_r($log_data_all);
                // $this->error();
                $result = false;
                $result = $row->allowField(true)->save($data);
                if ($result !== false) {
                    $this->addCheckLogMulti($row,$log_data_all);
                    $this->success();
                } else {
                    $this->error(__('No rows were updated'));
                }



            }
            else
                $this->error('参数不完整');
        }

        $this->success('ok', $row);
    }

    protected function  fieldWhere($library_id = 0) {
        $where['table_name'] = 'project';
        $where['status'] = 1;

        return $where;
    }



    protected function formatField(){

        $field_where = $this->fieldWhere($this->library_id);
        $fields_list = Fields::where($field_where)->order('weight','asc')->select();
        // echo Fields::getLastSql();
        $field = [];
        $rules = [];
        $rulesMessage = [];
        // $field['name'] = [
        //     'label' => '项目名称',
        //     'type' => 'string',
        //     'rule' => [],
        //     'class' => '',
        //     'group_style' => '',
        //     'required' => true,
        //     'pending' => 0,
        //     'sortable' => false,
        //     'filterable' => true,
        //     'op' => 'like',
        //     'viewable' => true,
        //     'editable' => true,
        //     'addable' => true,
        //     'showable' => true
        // ];
        // $rules['name'] = [
        //     'required'  => true
        // ];
        // pr($fields_list);
        foreach ($fields_list as $key => $value) {
            $field_name = '';
            if($value['item_type'] == 'select' || $value['item_type'] == 'selects')
                $field_name = str_replace('id','name', $value['item_id']);
            // if($value['item_type'] == 'date' || $value['item_type'] == 'datetime')
            //     $field_name = $value['item_id'].'_desc';
            $value['relation_value'] = '';
            $item_required = $value['item_required'] ? json_decode($value['item_required'],true):'';
            $value['item_data_msg'] = '';
            $value['group_style'] = '';

            if($item_required)
            {
                if(is_array($item_required)) {
                    $is_required = $item_required['is_required'];
                    $is_pending = $item_required['is_pending'];
                }
                else {
                    $is_required = $item_required;
                    $is_pending = 0;
                }

                $value['item_required'] = $is_required;
                $value['item_pending'] = $is_pending;
                // echo $item_required[$library_id]['is_required'];
                $value['item_data_rule'] = $is_required==1?'data-rule="required"':'';


            }else{
                $value['item_required'] = 0;
                $value['item_data_rule'] = '';
                $value['item_pending'] = 0;
            }
            if($value['item_rule'])
                $value['item_rule'] = json_decode($value['item_rule'],true);
            else
                $value['item_rule'] = [];

            if($value['item_type'] == 'text')
                $value['item_rule'] = empty($value['item_rule']) ? ['row'=>2]:$value['item_rule'];

            $item_rule = $value['item_rule'];

            // if($value['item_id'] == 'carrier_id'){
            //     $row['carrier_id_relation_unit'] = getRelationValue('carrier_id',$row['carrier_id']);
            //     $row['tmp_carrier_id_relation_unit'] = getRelationValue('carrier_id',$row['tmp_carrier_id']);
            // }


            if($field_name)
            {

                $field[$value['item_id']] = [
                    'label' => $value['item_label'],
                    'type' => $value['item_type'],
                    'rule' => $value['item_rule'],
                    'required' => $value['item_required']?true:false,
                    'class' => $value['item_class'],
                    'group_style' => $value['group_style'],
                    'sortable' => false,
                    'filterable' => $value['item_filterable']?true:false,
                    'op' =>  $value['item_op']?$value['item_op']:'',
                    'viewable' => false,
                    'editable' => true,
                    'addable' => true,
                    'showable' => true
                ];
                $field[$field_name] = [
                    'label' => $value['item_label'],
                    'type' => 'string',
                    'sortable' => false,
                    'filterable' => false,
                    'op' => false,
                    'viewable' => true,
                    'editable' => false,
                    'addable' => false,
                    'showable' => false
                ];

            }else
            {
                $field[$value['item_id']] = [
                    'label' => $value['item_label'],
                    'type' => $value['item_type'],
                    'rule' => $value['item_rule'],
                    'required' => $value['item_required']?true:false,
                    'class' => $value['item_class'],
                    'group_style' => $value['group_style'],

                    'sortable' => false,
                    'filterable' => $value['item_filterable']?true:false,
                    'op' =>  $value['item_op']?$value['item_op']:'',
                    'viewable' => true,
                    'editable' => true,
                    'addable' => true,
                    'showable' => true
                ];
            }
        }
        // pr($field);
        return ['field'=>$field,'rules'=>$rules ,'rulesMessage'=>$rulesMessage];
    }

     protected function addCheckLogMulti(\app\admin\model\Project $row,$dataAll=[]){
        // pr($dataAll);
        $userinfo = $this->getUserInfo();
        foreach ($dataAll as $key => $data) {
            if(isset($data['desc']))
                $operate_desc = $data['desc'];
            else
            {
                switch ($data['status']) {
                    case STATUS_SUBMIT:
                        $operate_desc = '提交';
                        // $operate_info = $row['tmp_'.$field.'_submit_desc'];
                        break;
                    case STATUS_PASS:
                        $operate_desc = '审核通过';
                        // $operate_info = '';
                        break;
                    case STATUS_REJECT:
                        $operate_desc = '驳回';
                        // $operate_info = $row['tmp_'.$field.'_reject_desc'];
                        break;
                    case STATUS_CREATE:
                        $operate_desc = '项目创建';
                        // $operate_info = $row['tmp_'.$field.'_reject_desc'];
                        break;
                    default:
                        $operate_desc = '';
                        break;
                }
            }
            $logData = [
                'project_pno' => $row->pno,
                'project_name'  => $row ->name,
                'operator_id'   => $userinfo -> id,
                'operator_nickname' => $userinfo ->  nickname,
                'operate_desc'  => $operate_desc,
                'operate_field' => $data['field'],
                'operate_field_label' =>isset($data['label'])?$data['label']:'',
                'operate_original_value' => isset($data['original_value'])?$data['original_value']:'',
                'operate_value' => isset($data['value'])?$data['value']:'',
                'operate_info' => isset($data['info'])?$data['info']:'',
                'operate_status' => $data['status'],
            ];
            \app\admin\model\ProjectChecklog::create($logData);
        }

    }


}